package com.xiaobai.mall.wrapper.autoconfigure;

import com.xiaobai.mall.common.domain.NonWrapper;
import com.xiaobai.mall.common.domain.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 全局controller返回值包装处理
 */
@RestControllerAdvice(annotations = Controller.class)
public class ResultWrapperAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, @NonNull Class converterType) {
        Method method = returnType.getMethod();
        Class<?> declaringClass = Objects.requireNonNull(method).getDeclaringClass();
        return !(method.isAnnotationPresent(NonWrapper.class) || declaringClass.isAnnotationPresent(NonWrapper.class));
    }

    @Override
    public Object beforeBodyWrite(Object body, @NonNull MethodParameter returnType, @NonNull MediaType selectedContentType, @NonNull Class selectedConverterType, @NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response) {
        return Result.buildSuccessResult(body);
    }
}
